package com.architecture.core.service.associate;

import com.architecture.core.entity.Group;
import com.architecture.core.entity.User;
import com.architecture.core.except.ErrException;
import com.architecture.core.service.AbstractService;
import com.architecture.core.utils.ErrCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: aguang
 * Date: 13-1-21
 * Time: 下午6:13
 * To change this template use File | Settings | File Templates.
 */
@Service("manageGroupService")
public class GroupAssociateService extends AbstractService {

    /**
     * 关联用户
     * @param groupId
     * @param userId
     * @throws ErrException
     */
    public void associateUser(String groupId,String userId) throws ErrException{

        if(StringUtils.isBlank(groupId)){
            throw new ErrException(ErrCode.BLANK_ID);
        }

        if (StringUtils.isBlank(userId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        Group group = (Group)baseDAO.findUnique(Group.class, groupId);

        User user = (User) baseDAO.findUnique(User.class, userId);

        group.getUserList().add(user);
        user.setGroup(group);

        super.baseDAO.update(group);
        super.baseDAO.update(user);

    }

    public void associateUser(String groupId,List<String> userIdList) throws ErrException{

        if(CollectionUtils.isEmpty(userIdList)) {
            throw new ErrException(ErrCode.EMPTY_COLLECTION);
        }

        for(String userId:userIdList){
            this.associateUser(groupId,userId);
        }
    }

    public void deassociateUser(String groupId,String userId) throws ErrException {

        if (StringUtils.isBlank(groupId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }
        if (StringUtils.isBlank(userId)) {
            throw new ErrException(ErrCode.BLANK_ID);
        }

        Group group = (Group)baseDAO.findUnique(Group.class, groupId);

        User user = (User) baseDAO.findUnique(User.class, userId);

        group.getUserList().remove(group);
        user.setGroup(null);

        super.baseDAO.update(group);
        this.baseDAO.update(user);

    }

    public void deassociateUser(String groupId,List<String> userIdList) throws ErrException{

        if(CollectionUtils.isEmpty(userIdList)) {
            throw new ErrException(ErrCode.EMPTY_COLLECTION);
        }

        for (String userId : userIdList) {
            this.deassociateUser(groupId,userId);
        }
    }

}
